package com.yuting.FileTools;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理文件的存入硬盘和读取到内存
 * @author cyt
 * @date 2020/7/2
 */
public class StoreAndReadFromFile {

    //将数据存入硬盘中
    public static <T> void InfoStoring(T t, String path){
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(path));
            objectOutputStream.writeObject(t);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != objectOutputStream){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //从文件中读取的信息
    public static Object readInfo(String path){
        File file = new File(path);
        if(file.exists()){
            ObjectInputStream ois = null;

            try {
                ois = new ObjectInputStream(new FileInputStream(path));
                Object object = ois.readObject();
                if(object instanceof List){
                    System.out.println("信息已读取");
                    return object;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                if(ois != null){
                    try {
                        ois.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                };

            }

        }
        System.out.println("读取失败！");
        return null;
    }
}
